package com.swz.dcrm.ui.analyze;


import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.pickerview.TimePickerView;
import com.bin.david.form.core.SmartTable;
import com.bin.david.form.core.TableConfig;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.IFormat;
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat;
import com.bin.david.form.data.format.bg.IBackgroundFormat;
import com.bin.david.form.data.format.bg.ICellBackgroundFormat;
import com.bin.david.form.data.format.count.ICountFormat;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.style.LineStyle;
import com.bin.david.form.data.table.TableData;
import com.bin.david.form.listener.OnColumnItemClickListener;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.CarModel;
import com.swz.dcrm.model.CustomerDefeated;
import com.swz.dcrm.model.HardWork;
import com.swz.dcrm.model.RankingListModel;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.AnalyzeViewModel;
import com.swz.dcrm.ui.viewmodel.CarBrandViewModel;
import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.util.Tool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class RankingListFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.table)
    SmartTable smartTable;
    @BindView(R.id.ll_date)
    LinearLayout llDate;
    @BindView(R.id.ll_car_model)
    LinearLayout llCarModel;
    @BindView(R.id.tv_car_model)
    TextView tvCarModel;

    private int type;
    private int click;
    private TimePickerView timePickerView;
    private Calendar calendar;
    List<String> titles;


    @Inject
    AnalyzeViewModel analyzeViewModel;
    @Inject
    CarBrandViewModel carBrandViewModel;
    private CarModel mCarModel;

    public static RankingListFragment newInstance() {

        return new RankingListFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        if (type == 0) {
            analyzeViewModel.getHardWorkingRankingList(tvStartTime.getText().toString(), tvEndTime.getText().toString())
                    .observe(this, listBaseResponse -> {
                        if (listBaseResponse == null) {
                            return;
                        }
                        if (listBaseResponse.isSuccess()) {
                            titles = Arrays.asList(getResources().getStringArray(R.array.analysis_type7));
                            Column name = new Column(titles.get(0), "name");

                            Column column1 = new Column(titles.get(1), "comeShopAndDriveCount");
                            Column column2 = new Column(titles.get(2), "beCallAndCallCount");
                            Column column3 = new Column(titles.get(3), "totalCount");

                            smartTable.setTableData(new TableData("", listBaseResponse.getData(), name, column1, column2, column3));
                        }

                    });
        } else if (type == 1 || type == 2) {
            analyzeViewModel.getSaleRankingList(tvStartTime.getText().toString(), tvEndTime.getText().toString(), type)
                    .observe(this, rankingListModelBaseResponse -> {
                        if (rankingListModelBaseResponse == null) {
                            return;
                        }
                        if (type == 1) {
                            titles = Arrays.asList(getResources().getStringArray(R.array.analysis_type6));
                        } else if (type == 2) {
                            titles = Arrays.asList(getResources().getStringArray(R.array.analysis_type8));
                        }
                        if (rankingListModelBaseResponse.isSuccess()) {
                            Column name = new Column(titles.get(0), "itemName");

                            Column column1 = new Column(titles.get(1), "count");
                            Column column2 = new Column(titles.get(2), "goalCount");
                            Column column3 = new Column(titles.get(3), "rate");
                            column3.setFormat(o -> o.toString() + "%");
                            rankingListModelBaseResponse.getData().getItemList().add(rankingListModelBaseResponse.getData().getAllStatisticsData());
                            smartTable.setTableData(new TableData("", rankingListModelBaseResponse.getData().getItemList(), name, column1, column2, column3));
                        }
                    });
        } else if (type == 3) {
            analyzeViewModel.getCancelOrder(tvStartTime.getText().toString(), tvEndTime.getText().toString())
                    .observe(this, listBaseResponse -> {
                        if (listBaseResponse == null) {
                            return;
                        }
                        if (listBaseResponse.isSuccess()) {
                            titles = Arrays.asList(getResources().getStringArray(R.array.analysis_type3));
                            Column name = new Column(titles.get(0), "itemName");

                            Column column1 = new Column(titles.get(1), "count");
                            Column column2 = new Column(titles.get(2), "goalCount");
                            Column column3 = new Column(titles.get(3), "rate");
                            column3.setOnColumnItemClickListener(new OnColumnItemClickListener() {
                                @Override
                                public void onClick(Column column, String value, Object o, int position) {

                                }
                            });
                            column3.setFormat(o -> o.toString() + "%");
                            smartTable.setTableData(new TableData("", listBaseResponse.getData(), name, column1, column2, column3));

                        }
                    });
        } else if (type == 4) {
            llCarModel.setVisibility(View.VISIBLE);
            if (mCarModel != null) {
                tvCarModel.setText(mCarModel.getName());
                analyzeViewModel.getCustomerDefeated(tvStartTime.getText().toString(), tvEndTime.getText().toString(), mCarModel.getId())
                        .observe(this, listBaseResponse -> {
                            if (listBaseResponse == null) {
                                return;
                            }
                            if (listBaseResponse.isSuccess()) {

                                titles = Arrays.asList(getResources().getStringArray(R.array.analysis_type2));
                                Column name = new Column(titles.get(0), "defeatedTypeName");

                                Column column1 = new Column(titles.get(1), "count");
                                Column column2 = new Column(titles.get(2), "rate");
                                column2.setFormat(o -> o.toString() + "%");
                                smartTable.setTableData(new TableData("", listBaseResponse.getData(), name, column1, column2));

                            }
                        });
            }
        } else if (type == 5) {
            analyzeViewModel.getStatisticsOrder()
                    .observe(this, listBaseResponse -> {
                        if (listBaseResponse == null) {
                            return;
                        }
                        if (listBaseResponse.isSuccess()) {

                            titles = Arrays.asList(getResources().getStringArray(R.array.analysis_type1));
                            Column name = new Column(titles.get(0), "name");

                            Column column1 = new Column(titles.get(1), "todayCount");
                            Column column2 = new Column(titles.get(2), "currentMonthCount");
                            Column column3 = new Column(titles.get(3), "currentSeasonCount");
                            Column column4 = new Column(titles.get(4), "currentYearCount");
                            smartTable.setTableData(new TableData("", listBaseResponse.getData(), name, column1, column2,column3,column4));

                        }
                    });

        }


    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_ranking_list;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        RankingListFragmentArgs rankingListFragmentArgs = RankingListFragmentArgs.fromBundle(getArguments());
        title.setText(rankingListFragmentArgs.getTitle());
        tvStartTime.setText(DateUtils.dateFormat(new Date(), "yyyy-MM"));
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
        tvEndTime.setText(DateUtils.dateFormat(calendar.getTime(), "yyyy-MM"));
        timePickerView = getTimePickerView((date, v) -> {
            if (click == 1) {
                tvStartTime.setText(DateUtils.dateFormat(date, "yyyy-MM"));
                onLoadRetry();
            } else {
                calendar.setTime(date);
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
                tvEndTime.setText(DateUtils.dateFormat(calendar.getTime(), "yyyy-MM"));
                onLoadRetry();
            }
        }).setType(new boolean[]{true, true, false, false, false, false}).build();
        if (rankingListFragmentArgs.getTitle().equals(getString(R.string.analysis_type6))) {
            type = 1;
        } else if (rankingListFragmentArgs.getTitle().equals(getString(R.string.analysis_type8))) {
            type = 2;
        } else if (rankingListFragmentArgs.getTitle().equals(getString(R.string.analysis_type3))) {
            type = 3;
        } else if (rankingListFragmentArgs.getTitle().equals(getString(R.string.analysis_type2))) {
            type = 4;
        } else if (rankingListFragmentArgs.getTitle().equals(getString(R.string.analysis_type1))) {
            llDate.setVisibility(View.GONE);
            type = 5;
        }
        if (type == 4) {
            carBrandViewModel.getSelectedCarModel().observe(this, carModel -> {
                if (carModel != null) {
                    mCarModel = carModel;
                    tvCarModel.setText(carModel.getName());
                    analyzeViewModel.getCustomerDefeated(tvStartTime.getText().toString(), tvEndTime.getText().toString(), carModel.getId())
                            .observe(this, listBaseResponse -> {
                                if (listBaseResponse == null) {
                                    return;
                                }
                                if (listBaseResponse.isSuccess()) {

                                    titles = Arrays.asList(getResources().getStringArray(R.array.analysis_type2));
                                    Column name = new Column(titles.get(0), "defeatedTypeName");

                                    Column column1 = new Column(titles.get(1), "count");
                                    Column column2 = new Column(titles.get(2), "rate");
                                    column2.setFormat(new IFormat() {
                                        @Override
                                        public String format(Object o) {
                                            return o.toString() + "%";
                                        }
                                    });
                                    smartTable.setTableData(new TableData("", listBaseResponse.getData(), name, column1, column2));

                                }
                            });

                }
            });

        }
        TableConfig tableConfig = smartTable.getConfig();
        tableConfig.setShowXSequence(false);
        tableConfig.setShowYSequence(false);
        tableConfig.setShowColumnTitle(true);
        smartTable.setZoom(true);
        FontStyle fontStyle = new FontStyle();
        fontStyle.setTextSpSize(getContext(), 14);
        tableConfig.setContentStyle(fontStyle);
        tableConfig.setColumnTitleBackground(new IBackgroundFormat() {
            @Override
            public void drawBackground(Canvas canvas, Rect rect, Paint paint) {
                paint.setColor(Color.WHITE);
                paint.setStyle(Paint.Style.FILL);
                canvas.drawRect(rect, paint);
            }
        });

        tableConfig.setColumnTitleVerticalPadding(Tool.dip2px(getActivity(), 16));
        tableConfig.setColumnTitleStyle(new FontStyle() {
            @Override
            public int getTextColor() {
                return ContextCompat.getColor(getContext(), R.color.gary_6f777d);
            }

            @Override
            public int getTextSize() {
                return Tool.dip2px(getActivity(), 14);
            }
        });

        tableConfig.setShowTableTitle(false);


        ICellBackgroundFormat<CellInfo> backgroundFormat = new BaseCellBackgroundFormat<CellInfo>() {
            @Override
            public int getBackGroundColor(CellInfo cellInfo) {

                return Color.parseColor("#ffffff");
            }

            @Override
            public int getTextColor(CellInfo cellInfo) {

                return ContextCompat.getColor(getContext(), R.color.black_2f3234);
            }
        };


        tableConfig.setMinTableWidth(Tool.dip2px(getActivity(), Tool.px2dip(getActivity(), Tool.getScreenWidth(getContext()))));
        tableConfig.setContentCellBackgroundFormat(backgroundFormat);

        tableConfig.setVerticalPadding(Tool.dip2px(getActivity(), 16));
        return true;
    }


    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick({R.id.tv_start_time, R.id.tv_end_time})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                click = 1;
                break;
            case R.id.tv_end_time:
                click = 2;
                break;
        }
        timePickerView.show();
    }

    @OnClick(R.id.ll_car_model)
    public void selectCar() {
        go(null, R.id.action_rankingListFragment_to_carBrandFragment, null);
    }
}
